<template>
  <div>
    <!-- 通知公告标题部分 -->
    <div class="notifications-title">
      <h2>通知公告</h2>
    </div>

    <!-- 通知表格部分 -->
    <div class="notifications-table">
      <el-row style="margin-top: 40px;">
        <el-table
            :data="paginatedNotificationsWithEmptyRows"
            :default-sort="{ prop: 'date', order: 'descending' }"
            stripe
            style="width: 100%"
            :row-style="setRowHeight"
        >
          <el-table-column prop="createTime" label="日期" width="180" />
          <el-table-column prop="title" label="标题" width="180" />
          <el-table-column prop="content" label="内容" />
          <el-table-column label="操作" width="180">
            <template v-slot="scope">
              <div style="display: flex; gap: 5px;">
                <el-button
                    v-if="scope.row.id"
                    size="mini"
                    type="primary"
                    @click="viewNotificationDetail(scope.row)"
                    style="padding: 6px 8px; font-size: 12px;"
                >
                  查看详情
                </el-button>
                <el-button
                    v-if="scope.row.id"
                    size="mini"
                    @click="markAsRead(scope.row.id)"
                    style="padding: 6px 8px; font-size: 12px;"
                >
                  标为已读
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <!-- 分页 -->
      <el-row style="margin-top: 20px; justify-content: center;">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="notifications.length"
            :page-size="pageSize"
            @current-change="handlePageChange"
        />
      </el-row>
    </div>

    <!-- 通知详情对话框 -->
    <el-dialog :visible.sync="isDialogVisible" title="通知详情">
      <p><strong>标题:</strong> {{ selectedNotification.title }}</p>
      <p><strong>日期:</strong> {{ formatDate(selectedNotification.date) }}</p>
      <p><strong>内容:</strong> {{ selectedNotification.content }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import {BASE_URL} from "@/config";

export default {
  setup() {
    const notifications = ref([]);
    const selectedNotification = ref({});
    const isDialogVisible = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);

    const paginatedNotifications = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = currentPage.value * pageSize.value;
      return notifications.value.slice(start, end);
    });

    const paginatedNotificationsWithEmptyRows = computed(() => {
      const notificationsPage = paginatedNotifications.value;
      const emptyRows = Array(pageSize.value - notificationsPage.length).fill({
        createTime: '',
        title: '',
        content: '',
        id: null,
      });
      return [...notificationsPage, ...emptyRows];
    });

    const setRowHeight = () => {
      return {
        height: '50px',
      };
    };

    const fetchNotifications = async () => {
      try {
        console.log("获取通知信息")
        const response = await axios.post(`${BASE_URL}/notifications/all`);
        notifications.value = response.data.data.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
      } catch (error) {
        console.error('获取通知信息失败:', error);
      }
    };

    const markAsRead = async (id) => {
      try {
        const response = await axios.put(`http://localhost:8000/api/notifications/${id}/read`);
        if (response.status === 200) {
          const notification = notifications.value.find((n) => n.id === id);
          notification.isRead = true;
        }
      } catch (error) {
        console.error('标记通知为已读失败:', error);
      }
    };

    const viewNotificationDetail = (notification) => {
      selectedNotification.value = notification;
      isDialogVisible.value = true;
    };

    const formatDate = (dateStr) => {
      const date = new Date(dateStr);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    onMounted(() => {
      fetchNotifications();
    });

    return {
      notifications,
      selectedNotification,
      isDialogVisible,
      markAsRead,
      viewNotificationDetail,
      formatDate,
      currentPage,
      pageSize,
      paginatedNotifications,
      paginatedNotificationsWithEmptyRows,
      handlePageChange,
      setRowHeight,
    };
  },
};
</script>

<style scoped>
.notifications-page {
  padding: 20px;
  background-color: #f7f7f7;
}

.notifications-title {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.notifications-title h2 {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin: 0;
}

.notifications-table {
  margin-top: 20px;
}

.notifications-table .el-table th,
.notifications-table .el-table td {
  text-align: center;
}
</style>
